# -- coding: utf-8 --
import shutil, os, traceback, sys, time, stat
import ConfigParser
import urllib, urllib2
import codecs
from subprocess  import *

#sync gerrit code to huawei master
class merge_code():
    #excute shell cmd        
    def _shell_cmd(self, s_cmd_line, inmsg=None, wait_res = True,need_log = True,ignore = False,time_out = None):
        if True == True:
            print 's_cmd_line: ' + s_cmd_line
        p= Popen(s_cmd_line, stdin=PIPE,stdout=PIPE,stderr=PIPE,shell=True)
        if inmsg:
            p.stdin.write(inmsg)
        if wait_res == False:
            return 0,'',''
        if time_out is not None:
            kill = lambda process: process.kill()
            my_timer = Timer(time_out, kill, [p])
            try:
                my_timer.start()
                out,err=p.communicate()
            finally:
                my_timer.cancel()
        else:
            out,err=p.communicate()
        new_out = ''
        new_err = ''
        try:
            new_out = out.decode('gb2312')
        except:
            try:
                new_out = out.decode('utf8')
            except:
                pass
        try:
            new_err = err.decode('gb2312')
        except:
            try:
                new_err = err.decode('utf8')
            except:
                pass
        if p.returncode != 0 and ignore == False:
            try:
                print 'exec cmd fail,the cmdline is ' + s_cmd_line + ',returncode is ' + str(p.returncode) + ',err is ' + str(err) + ',out is ' + str(out)
            except:
                print 'exec cmd fail,the cmdline is ' + s_cmd_line + ',returncode is ' + str(p.returncode) + ',err is ' + str(new_err) + ',out is ' + str(new_out)
        elif need_log == True:
            try:
                print 'exec cmd success,the cmdline is ' + s_cmd_line + ',err is ' + str(err) + ',out is ' + str(out)
            except:
                print 'exec cmd success,the cmdline is ' + s_cmd_line + ',err is ' + str(new_err) + ',out is ' + str(new_out)
        return p.returncode,out,err
    
    def _gen_commit_patchs(self, gerrit_save_path, patch_save_path, branch ,dst_branch):
        curr_dir = os.getcwd()
        #reset patchs's dir
        if os.path.isdir(patch_save_path):
            shutil.rmtree(patch_save_path)
        try:
            os.makedirs(patch_save_path)
        except:
            time.sleep(5)
            if not os.path.isdir(patch_save_path):
                os.makedirs(patch_save_path)
        os.chdir(gerrit_save_path)
        ret,out,err = self._shell_cmd('git checkout ' + dst_branch)
        ret,out,err = self._shell_cmd('git pull ')
        ret,msg_list,err = self._shell_cmd('git log -10 --no-merges --pretty=format:"%B"', need_log = False)
        if ret != 0:
            return ret, err
        print "gerrit_proj_path = "+ gerrit_save_path
        ret,out,err = self._shell_cmd('git checkout ' + branch)
        ret,out,err = self._shell_cmd('git pull ')
        change_id = ''
        commit_id = ''
        if 'Change-Id: ' in msg_list:
            #get the latest change_id of dst_branch
            change_id = msg_list.split('Change-Id: ')[1].split('\n')[0].replace('\r','')
            if change_id == '':
                print dst_branch + ': change_id is null'
                return 1,''
            ret,out,err = self._shell_cmd('git log -10 --no-merges')
            if ret != 0:
                return ret, out
            #get the commit_id on branch matchs latest change_id
            commit_id = out.split(change_id)[0].split('Change-Id:')[-2].split('Author:')[0].split('commit')[-1].split('\n')[0].replace('\r','').replace(' ','')
        print 'change-id from ' + dst_branch + ': ' + change_id
        print 'commit-id found from ' + branch + ': ' + commit_id
        ret,out,err = self._shell_cmd('git log --no-merges --topo-order --since="6months" --pretty=format:"%H"', need_log = False)
        #calculate the num. of patchs to be generated
        if ret != 0:
            return ret, out
        if commit_id == '':  
            print 'This is the first time to merge code to dst_branch.'
            commit_num = len(out.split('\n'))
        else:
            print 'Normal merge.'
            commit_num = len(out.split(commit_id)[0].split('\n'))
        print 'The patchs count is : ' + str(commit_num)
        ret,out,err = self._shell_cmd('git format-patch --topo-order -%s -o %s' % (commit_num,patch_save_path), need_log = False)
        if ret != 0:
            return ret, out
        os.chdir(curr_dir)
        return 0,commit_id
    
    def _push_commit(self, gerrit_save_path, patch_save_path, last_commit_id, commit_file_path, branch ,dst_branch):
        curr_dir = os.getcwd()
        gerrit_commit = True
        patch_lst = os.listdir(patch_save_path)
        patch_lst.sort()
        if len(patch_lst) == 0:
            print'_push_commit: no patch'
            return 1
        start_idx = 0
        first_patch_obj = open(patch_save_path + '/' + patch_lst[0],'r')
        first_patch_content = first_patch_obj.readline()
        first_patch_obj.close()
        print '_push_commit:the first patch is ' + patch_lst[0]
        print '_push_commit:the last_commit_id is ' + last_commit_id
        if last_commit_id !='' and last_commit_id not in first_patch_content:
            print '_push_commit:last_commit_id is not in the first patch.'
            return 1
        elif last_commit_id !='':
            print '_push_commit:the first patch has been merged to ' + dst_branch
            start_idx = 1
        ret = 0
        for patch in patch_lst[start_idx:]:
            print '_push_commit: patch = ' + patch
            patch_path = patch_save_path + '/' + patch
            print '_push_commit: patch_path = ' + patch_path
            patch_obj = open(patch_path,'r')
            patch_lines = patch_obj.readlines()
            patch_obj.close()
            if os.path.getsize(patch_path):
                print "This commit is valid."
            else:
                print "This commit is empty."
                continue
            commit_id = patch_lines[0].split(' ')[1]
            if commit_id == '':
                print '_push_commit:commit_id is null'
                ret = 1
                break
            change_id = ''
            for line in patch_lines:
                if 'Change-Id: ' in line:
                    change_id = line.split(' ')[1].replace('\r','').replace('\n','')
                    break
                if 'diff --git ' in line:
                    break
            if change_id == '':
                print'_push_commit:change_id is null,the patch is ' + patch
                break
            print '_push_commit: the change_id is ' + change_id
            ret,out,err = self._shell_cmd('curl http://dgggit09-rd.huawei.com/changes/' + change_id)
            if 'Not found:' in out:
               ret,out,err = self._shell_cmd('curl http://dgggit09-rd.huawei.com/changes/?q=commit:\''+commit_id+'\'')
               if '_number' not in out:
                   ret,out,err = self._shell_cmd('ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query commit:\''+commit_id+'\'')
                   if ret != 0:
                       return ret
            ID=''
            if '_number' in out:
                ID = out.split("_number")[1].split(' ')[1].split('\n')[0].replace(' ','').replace(',','')
            elif 'number' in out:
                ID = out.split("number:")[1].split(' ')[1].split('\n')[0].replace(' ','').replace(',','')
            else:
                print 'Error: get ID failed.'
                ret = 1
                break
            if ID is None:
                print 'Error: ID is null'
                gerrit_commit = False
            print 'generate_comment: _push_commit'
            ret,owner = self._generate_comment(gerrit_save_path, commit_file_path, branch, ID)
            if ret != 0:
               print "generate_comment error !"
               return ret
            if owner is None:
                print "get owner failed"
                return 1
            os.chdir(gerrit_save_path)
            ret,out,err = self._shell_cmd('git checkout ' + dst_branch)
            if ret != 0:
               return ret
            ret,out,err = self._shell_cmd('git pull ')
            if ret != 0:
               return ret
            ret,out,err = self._shell_cmd('git apply --ignore-whitespace --whitespace=fix ' + patch_path)
            if ret != 0:
               return ret
            print 'Current dir is  ' + gerrit_save_path
            print '_push_commit: ret = ' + str(ret)
            print '_push_commit: out = ' + str(out)
            if ret != 0:
                print '_push_commit:apply patch fail: ' + patch_path + ',the err is ' + err
                return ret
            ret,out,err = self._shell_cmd('git add ./ ')
            if ret != 0:
                return ret
            name = owner.split('name:')[1].split('\n')[0]
            email = owner.split('email:')[1].split('\n')[0]
            accunt = name.split(' ')[1].strip()
            user_name = email.split('@')[0].strip()
            if 'xudengfeng' not in owner:
                ret,out,err = self._shell_cmd("sed -i 's/NAME/" + user_name + "/g' /root/.gitconfig")
                if ret != 0:
                    ret,out,err = self._shell_cmd("sed -i 's/NAME/" + user_name + "/g' /root/.gitconfig")
                    if ret != 0:
                        return ret
                ret,out,err = self._shell_cmd("sed -i 's/ACCOUNT/" + accunt + "/g' /root/.gitconfig")
                if ret != 0:
                    ret,out,err = self._shell_cmd("sed -i 's/ACCOUNT/" + accunt + "/g' /root/.gitconfig")
                    if ret != 0:
                        ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                        return ret
                ret,out,err = self._shell_cmd('git config user.name ' + name)
                if ret != 0:
                    ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                    ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                    return ret
                ret,out,err = self._shell_cmd('git config user.email ' + email)
                if ret != 0:
                    ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                    ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                    return ret
            ret,out,err = self._shell_cmd('git commit -a -F ' + commit_file_path + '')
            if ret != 0:
                print '_push_commit:commit patch failed,the out is ' + out + ',the err is ' + err
                ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                ret = 1
                break
            ret,out,err = self._shell_cmd('git push ')
            if ret != 0:
                print '_push_commit:push patch failed,the err is ' + err
                ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                ret = 1
                break
            ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
            if ret != 0:
                ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                return ret
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            if ret != 0:
                ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                return ret
        os.chdir(gerrit_save_path)
        ret,out,err = self._shell_cmd('git checkout ' + branch)
        os.chdir(curr_dir)
        return ret

    def _merge_one_module(self, project, branch, dst_branch, change_number):
        base_url = "http://dgggit09-rd.huawei.com/a/"
        merge_path = '/usr1/merge_code_dir_Euler_v3r1'
        worker_path = merge_path + '/' + branch
        patch_save_path = worker_path + '/patchs'
        commit_file_path = worker_path + '/comment.txt'
        gerrit_proj_path = ''
        if not os.path.isdir(worker_path):
            os.makedirs(worker_path)
        if not os.path.isdir(patch_save_path):
            os.makedirs(patch_save_path)
        #sync gerrit code
        work_dir = os.getcwd()
        os.chdir(worker_path)
        print 'Workspace is ' + os.getcwd()
        if 'next' == branch:
            xml_file = 'EulerOS_next.xml'
        else:
            print "Not next , skip."
            return 0
        if not os.path.isdir(worker_path + '/.repo'):
            shutil.rmtree(worker_path)
            os.makedirs(worker_path)
            os.makedirs(patch_save_path)
            os.chdir(worker_path)
            try:
                cmd = 'bash -x ' + work_dir + '/init_repo_euleros.sh ' + worker_path + ' ' + xml_file
                ret,out,err = self._shell_cmd(cmd)
                if ret !=0:
                    return ret
            except:
                print 'Repo. init failed:'
                print "".join(traceback.format_exception(*sys.exc_info()))
                return ret
        #update gerrit code
        print 'Current dir is ' + os.getcwd()
        if 'next' != branch:
            cmd = 'cat .repo/manifests/' + xml_file + ' | grep -w ' + '\'<include\''
            ret,out,err = self._shell_cmd(cmd)
            out = out.strip()
            if ret == 0:
                cmd = 'echo ' + '\'' + out + '\' | awk -F \'"\' \'{print $2}\''
                ret,out,err = self._shell_cmd(cmd)
                if ret !=0:
                    return ret
                out = out.strip()
                xml_file =  out
            elif ret != 1:
                return ret
            cmd = 'cat .repo/manifests/' + xml_file + ' | grep -w ' + '\'name="' + project +'"\''
            ret,out,err = self._shell_cmd(cmd)
            if ret !=0:
                return ret
        else:
            cmd = 'grep -w ' + '\'name="' + project +'"\' .repo/manifests/EulerOS_self_src_next.xml .repo/manifests/EulerOS_open_source_next.xml'
            ret,out,err = self._shell_cmd(cmd)

        out = out.strip()
        print 'out = ' + out
        print 'ret = ' + str(ret)
        print 'err = ' + str(err)
        if ret != 0:
            print " Do not find [ " + project + " ] in euleros' xml, Skip"
            return 0
        elif len(out.split('\n')) > 1:
            if out.split('\n')[2] is not None:
                print "Warning: module " + project + " is duplicated, please check it in branch xml"
                return 1
        proj_path = out.split('path=')[1].split('"')[1].strip()
        gerrit_proj_path = worker_path + '/' + proj_path
        print 'gerrit_proj_path = ' + gerrit_proj_path

        if not os.path.isdir(gerrit_proj_path):
            ret,out,err = self._shell_cmd('repo sync --no-tags ' + project)
            if ret !=0:
                print 'repo sync project failed'
                return ret
            ret,out,err = self._shell_cmd('repo start --all ' + branch)
            if ret !=0:
                return ret
            os.chdir(gerrit_proj_path)
        else:
            os.chdir(gerrit_proj_path)
            ret,out,err = self._shell_cmd('git checkout ' + branch)
            ret,out,err = self._shell_cmd('git pull')
            if ret !=0:
                return ret
   
        #update <dst_branch>
        git_url = base_url + project
        ret,out,err = self._shell_cmd('git branch -a | grep remotes/rtos_v2/' + dst_branch)
        if dst_branch in out:
            ret,out,err = self._shell_cmd('git branch -a | grep remotes/code/' + dst_branch)
            if dst_branch in out:
                ret,out,err = self._shell_cmd('git checkout ' + branch)
                if ret !=0:
                    return ret
                ret,out,err = self._shell_cmd('git branch -D ' + dst_branch)
                ret,out,err = self._shell_cmd('git remote remove code')
                if ret !=0:
                    return ret
            ret,out,err = self._shell_cmd('git branch | grep ' + dst_branch)
            if ret != 0:
                ret,out,err = self._shell_cmd('git checkout -b ' + dst_branch + ' remotes/rtos_v2/' + dst_branch)
                if ret !=0:
                    print 'init dst_branch failed'
                    return ret 
        #init new branch
        else:
            ret = self._merge_code(git_url, gerrit_proj_path, commit_file_path, branch, dst_branch, change_number)
            return ret
        if project == 'euleros/tools/obs_meta':
            ret = self._merge_special_module(gerrit_proj_path, branch ,dst_branch)
            return ret
        #generate patchs and get the last commit-id from branch (vs dst_branch)
        print 'gen_commit_patchs begin'
        ret,last_commit_id = self._gen_commit_patchs(gerrit_proj_path, patch_save_path, branch ,dst_branch)
        if ret !=0:
            print 'exec: _gen_commit_patchs returns an error.'
            return ret
        #get reviewers info and commit patchs to dst branch
        if last_commit_id == '':
            print "last_commit_id is null, Something wrong happened on branch: " + dst_branch
            return 1
        else:
            ret = self._push_commit(gerrit_proj_path, patch_save_path, last_commit_id, commit_file_path, branch ,dst_branch)
        return ret

    def _merge_code(self, git_url, gerrit_pro_path, commit_file_path, branch, dst_branch, change_number):
        os.chdir(gerrit_pro_path)
        ret,out,err = self._shell_cmd('git checkout ' + branch)
        out = ''
        #remove remote info
        ret,out,err = self._shell_cmd("git remote -v | awk '{print $1}' | grep code")
        if  'code' == out.strip():
            ret,out,err = self._shell_cmd('git branch | grep ' + dst_branch)
            if dst_branch == out.strip():
                ret,out,err = self._shell_cmd('git branch -D ' + dst_branch)
            ret,out,err = self._shell_cmd('git remote remove code ')
            if ret != 0:
                return ret
        #generate comment.txt
        print 'generate_comment: _merge_code'
        ret,owner = self._generate_comment(gerrit_pro_path, commit_file_path, branch, change_number)
        if ret != 0:
            print "generate_comment error !"
            return ret
        if owner is None:
            print "get owner failed"
            return 1
        #create remote branch
        ret,out,err = self._shell_cmd('git remote add code ' + git_url)
        if ret != 0:
            return ret
        ret,out,err = self._shell_cmd('git fetch code')
        if ret != 0:
            return ret
        ret,out,err = self._shell_cmd('git checkout -b ' + dst_branch + ' remotes/code/' + branch)
        if ret != 0:
            return ret
        ret,out,err = self._shell_cmd('git pull  ')
        if ret != 0:
            return ret
        #usually , nothing to merge ,so git-commit would faile that is accectable
        name = owner.split('name:')[1].split('\n')[0]
        email = owner.split('email:')[1].split('\n')[0]
        accunt = name.split(' ')[1].strip()
        user_name = email.split('@')[0].strip()
        if 'xudengfeng' not in owner:
            ret,out,err = self._shell_cmd("sed -i 's/NAME/" + user_name + "/g' /root/.gitconfig")
            if ret != 0:
                ret,out,err = self._shell_cmd("sed -i 's/NAME/" + user_name + "/g' /root/.gitconfig")
                if ret != 0:
                    return ret
            ret,out,err = self._shell_cmd("sed -i 's/ACCOUNT/" + accunt + "/g' /root/.gitconfig")
            if ret != 0:
                ret,out,err = self._shell_cmd("sed -i 's/ACCOUNT/" + accunt + "/g' /root/.gitconfig")
                if ret != 0:
                    ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                    return ret
            ret,out,err = self._shell_cmd('git config user.name ' + name)
            if ret != 0:
                ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                return ret
            ret,out,err = self._shell_cmd('git config user.email ' + email)
            if ret != 0:
                ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
                ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
                return ret
        ret,out,err = self._shell_cmd('git commit --amend -F ' + commit_file_path)
        if ret != 0:
            ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            return ret
        ret,out,err = self._shell_cmd('git push code ' + dst_branch + ':' + dst_branch)
        if ret != 0:
            ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            return ret
        #remove remote info
        ret,out,err = self._shell_cmd('git checkout ' + branch)
        if ret != 0:
            ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            return ret
        ret,out,err = self._shell_cmd('git branch -D ' + dst_branch)
        ret,out,err = self._shell_cmd('git remote remove code ')
        if ret != 0:
            ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            return ret
        ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
        if ret != 0:
            ret,out,err = self._shell_cmd("sed -i 's/" + user_name + "/NAME/g' /root/.gitconfig")
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            return ret
        ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
        if ret != 0:
            ret,out,err = self._shell_cmd("sed -i 's/" + accunt + "/ACCOUNT/g' /root/.gitconfig")
            return ret
        return 0

    def _merge_special_module(self, gerrit_pro_path, branch ,dst_branch):
        cur_dir = os.getcwd()
        os.chdir(gerrit_pro_path)
        ret,out,err = self._shell_cmd("git checkout " + branch)
        if ret != 0:
            print '_merge_special_module: git checkout failed'
            return ret
        ret,out,err = self._shell_cmd("git pull ")
        if ret != 0:
            print '_merge_special_module: git pull failed'
            return ret
        ret,out,err = self._shell_cmd("git checkout " + dst_branch)
        if ret != 0:
            print '_merge_special_module: git checkout failed'
            return ret
        ret,out,err = self._shell_cmd("git pull ")
        if ret != 0:
            print '_merge_special_module: git pull failed'
            return ret
        ret,out,err = self._shell_cmd("git merge next -m 'merge form src_branch'")
        if ret != 0:
            print '_merge_special_module: git merge failed'
            return ret
        ret,out,err = self._shell_cmd("git push  ")
        if ret != 0:
            print '_merge_special_module: git push failed'
            return ret
        ret,out,err = self._shell_cmd("git checkout " + branch)
        if ret != 0:
            print '_merge_special_module: git checkout failed'
            return ret
        return 0


    def _generate_comment(self, gerrit_pro_path, commit_file_path, branch, change_number):
        ret,result,err = self._shell_cmd('ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query --all-reviewers change:' + change_number)
        print '_generate_comment: query result = ' + result
        if ret != 0:
            print 'gerrit query failed'
            return ret,''
        if result is None:
            print '_generate_comment: get reviewers failed.'
            return 1,''
        owner = result.split('owner:')[1].split('url:')[0]
        print '_generate_comment: owner = ' + owner
        reviewers = ''
        reviewers_list = result.split('allReviewers:')[1:]
        for item in range(len(reviewers_list)):
            if 'Jenkins' in reviewers_list[item]:
                continue
            if 'public rtosci' in reviewers_list[item]:
                continue
            if owner in reviewers_list[item] and 'EulerOS_test' not in branch:
                continue
            if "name" not in reviewers_list[item]:
                continue
            reviewers = reviewers + reviewers_list[item].split('name:')[1].split('\n')[0]
            reviewers = reviewers + ' '
        if reviewers == '':
            print 'Error: reviewers is none!'
            return 1,''
        create_time = result.split('createdOn:')[1].split('\n')[0]
        last_time = result.split('lastUpdated:')[1].split('\n')[0]
        commit_msg = result.split('commitMessage:')[1].split('createdOn:')[0]
        #os.chdir(gerrit_pro_path)
        #ret,out,err = self._shell_cmd("git branch | awk '{print $2}'")
        #cur_branch = out.strip()
        #ret,out,err = self._shell_cmd('git checkout ' + branch)
        #ret,out,err = self._shell_cmd('git pull ')
        #ret,commit_msg,err = self._shell_cmd('git log -1 --no-merges --pretty=format:"%B"', need_log = False)
        #if ret != 0:
        #    print 'git log -1 failed'
        #    return ret,''
        #ret,out,err = self._shell_cmd('git checkout ' + cur_branch)
        #if ret != 0 :
        #    print 'git checkout cur_branch failed'
        #    return 1,''
        comment_obj = open(commit_file_path,'w')
        comment_obj.write(commit_msg)
        if 'Signed-off-by' not in commit_msg:
            comment_obj.write('\nSigned-off-by:' + owner.split('name:')[1].split('\n')[0] + ',Signed-off-time:' + create_time)
        comment_obj.write('\nReviewed-by:' + reviewers + ',Reviewed-time:' + last_time)
        comment_obj.close()
        comment_obj = open(commit_file_path)
        msg = comment_obj.read()
        print '------------------------------------dubug------'
        print 'commit msg: ' + str(msg)
        comment_obj.close()
        print '------------------------------------dubug------'
        return 0,owner
 
    def execute(self,project, branch, dst_branch,change_number):
        ret = 0
        try:
            print 'the time is ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ',start to sync the module:' + project + ', from ' + branch + ' to ' + dst_branch
            ret = self._merge_one_module(project, branch, dst_branch, change_number)
            print 'the time is ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ',end sync the module:' + project + ', from ' + branch + ' to ' + dst_branch
        except:
            print "".join(traceback.format_exception(*sys.exc_info()))
        return ret
if __name__ == '__main__':
    #pass
    if len(sys.argv) < 3:
        print 'Error: please input project name and gerrit branch'
        sys.exit(1)
    project = sys.argv[1]
    branch = sys.argv[2]
    change_number = sys.argv[3]
    dst_branch_list = ['next_add_reviewer']
    result = 0
    merge_obj = merge_code()
    for dst_branch in dst_branch_list:
        ret = merge_obj.execute(project, branch, dst_branch, change_number)
        if 0 != ret:
            print 'ERROR: sync ' + project + ', from ' + branch + ' to ' + dst_branch + " failed."
        result = ret + result
    sys.exit(result)











